package com.wbsxch.example.springsecurity.config.authentication;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wbsxch.example.springsecurity.entity.Permission;
import com.wbsxch.example.springsecurity.entity.User;
import com.wbsxch.example.springsecurity.service.UserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class SecurityUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
        if(user == null){
            throw new UsernameNotFoundException(username);
        }
        List<Permission> permissions = userService.selectPermissionByUserId(user.getId());
        List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission -> new SimpleGrantedAuthority(permission.getCode())).collect(Collectors.toList());

        return SecurityUser.builder()
                .username(user.getUsername())
                .password(new BCryptPasswordEncoder().encode(user.getPassword()))
                .enabled(user.getStatus() == 1)
                .authorities(authorities)
                .build();
    }
}
